package org.java.user.controller;

import org.java.commons.vo.Result;
import org.java.user.api.damain.User;
import org.java.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;


@Controller
@RequestMapping("/registry")
public class RegistryController {
    @Autowired
    private UserService userService;

    //显示前端页面，需要增加JSP引擎、配置视图解析器
    @RequestMapping(method = RequestMethod.GET)
    private String registry() {
        return "registry";
    }

    @RequestMapping(method = RequestMethod.POST)
    private ModelAndView registry(User user, String password2) {
        Result result = this.registry2(user, password2);
        ModelAndView mav = new ModelAndView();
        mav.addObject("result", result);
        if (result.getCode() == 1) {
            // 成功
            mav.setViewName("success");
        } else {
            // 失败
            mav.setViewName("registry");
        }
        return mav;

    }
    // 给前后端分离时使用的
    @RequestMapping(method = RequestMethod.POST, produces = "application/json")
    @ResponseBody
    private Result registry2(User user, String password2) {
        Result result;
        if (StringUtils.isEmpty(password2)) {
            // 没有输入确认密码，不能注册
            result = Result.error("请在【确认密码】框中再次输入相同的密码");
        } else if (!password2.equals(user.getPassword())) {
            // 两次输入的密码不同，不能注册
            result = Result.error("请在【确认密码】框中再次输入相同的密码");
        } else {
            // 表示可以注册
            result = userService.registry(user);
        }
        return result;
    }
}
